package bill_management

import (
	"github.com/gin-gonic/gin"
	"log"
	"strconv"
	"tao-admin/configs"
	"tao-admin/internal/model"
)

type BillManager struct{}

type SearchBillCondition struct {
	Type   *int64  `gorm:"column:type" json:"type"`
	Value  *int64  `gorm:"column:value" json:"value"`
	Tags   *string `gorm:"column:tags" json:"tags"`
	Remark *string `gorm:"column:remark" json:"remark"`
	Date   *string `gorm:"column:date" json:"date"`
	Ctime  *int64  `gorm:"column:ctime" json:"ctime"`
	Mtime  *int64  `gorm:"column:mtime" json:"mtime"`
}

func (m *BillManager) SearchBillByConditionMng(ctx *gin.Context, condition *SearchBillCondition) ([]model.BillTab, int64, error) {
	page, _ := strconv.Atoi(ctx.Query("page"))
	count, _ := strconv.Atoi(ctx.Query("perPage"))

	db := configs.GetGormDB()
	list := make([]model.BillTab, 0)
	var total int64 = 0

	if condition.Type != nil {
		db = db.Where("type=?", condition.Type)
	}
	if condition.Value != nil {
		db = db.Where("value=?", condition.Value)
	}
	if condition.Tags != nil {
		db = db.Where("tags=?", condition.Tags)
	}
	if condition.Remark != nil {
		db = db.Where("remark=?", condition.Remark)
	}
	if condition.Date != nil {
		db = db.Where("date=?", condition.Date)
	}
	if condition.Ctime != nil {
		db = db.Where("ctime=?", condition.Ctime)
	}
	if condition.Mtime != nil {
		db = db.Where("mtime=?", condition.Mtime)
	}

	err1 := db.Model(&model.BillTab{}).Count(&total).Error
	if page > 0 && count > 0 {
		db = db.Limit(count).Offset((page - 1) * count)
	}

	//db = db.Order("priority DESC, status ASC")
	db = db.Order("id DESC")

	err2 := db.Find(&list).Error
	if err1 != nil || err2 != nil {
		return nil, 0, nil
	}

	log.Printf("查表结束, list: %v", list)
	return list, total, nil
}

func (m *BillManager) CreateBillMng(ctx *gin.Context, item model.BillTab) error {
	db := configs.GetGormDB()
	err := db.Create(&item).Error
	if err != nil {
		return err
	}
	return nil
}

func (m *BillManager) UpdateBillMng(ctx *gin.Context, item model.BillTab) error {
	db := configs.GetGormDB()
	// 先赋值
	updateData := model.BillTab{
		Type:   item.Type,
		Value:  item.Value,
		Tags:   item.Tags,
		Remark: item.Remark,
		Date:   item.Date,
		Ctime:  item.Ctime,
		Mtime:  item.Mtime,
	}

	id := item.Id
	// 查询记录
	if err := db.Where("id = ?", id).First(&item).Error; err != nil {
		return err
	}

	err := db.Model(&item).Where("id = ?", id).Update(updateData).Error
	if err != nil {
		return err
	}
	return nil
}

func (m *BillManager) DeleteBillMng(ctx *gin.Context, item model.BillTab) error {
	db := configs.GetGormDB()
	id := item.Id
	// 查询记录
	if err := db.Where("id = ?", id).First(&item).Error; err != nil {
		return err
	}
	err := db.Delete(&item).Error
	if err != nil {
		return err
	}
	return nil
}
